module.exports = function(options) {

    const cookieKey = options.key || "MewSID";
    const keys_can_delete = options.keys_can_delete || []
    let delete_map = keys_can_delete.reduce((result, key) => {
        result[key] = {}
        return result
    }, {})

    const timeout = options.timeout || 20 * 60 * 1000;
    const sessionPool = @.mem.cachePool(timeout);

    @heard("lab.session.delete").then(function(mew) {
        let { key, id } = mew.content["lab.session.delete"]
        if (key && id) {
            let key_name = key.split(":")[0]
            if (key_name && delete_map[key_name]) {
                let sessionIDs = delete_map[key_name][id]
                if (sessionIDs) {
                    sessionIDs.forEach(function(sessionID) {
                        let session = sessionPool.get(sessionID, true, function() {
                            return Object.create(null);
                        });
                        key.split(":")[1].split(",").forEach(function(sessionKey) {
                            if (session[sessionKey]) {
                                delete session[sessionKey]
                            }
                        })
                    })
                }
                delete_map[key_name][id] = []
            }
        }
    })

    return function(request, response) {

        let sid = request.cookies[cookieKey];
        if (!sid) {
            sid = @.uuid();
            response.cookies[cookieKey] = sid;
        }

        let session = sessionPool.get(sid, true, function() {
            return Object.create(null);
        });

        keys_can_delete.forEach(function(key) {
            let key_name = key.split(":")[0]
            let key_id = key_name.split(".").reduce((target, k) => {
                return target && target[k] ? target[k] : null
            }, session)
            if (key_id) {
                if (!delete_map[key_name][key_id]) {
                    delete_map[key_name][key_id] = []
                }
                delete_map[key_name][key_id].push(session.id)
            }
        })

        return session;

    };
}